const util = require('../../../utils/util.js');
const barTitleText = ['车辆上门', '车辆情况', '交强险保单（及车船税）','联系人'];
const app = getApp();
const extraList = ['投保', '不投保'];
const carStatusDetailList = [
  { value: '正常', text: '正常', checked: 'true' },
  { value: '个别异常', text: '个别异常' }
];
Page({
  data: {
    price: 0,
    name:'compulsoryOrderPhoto',
    agreeCheck:false,
    verificationInfo: {
      isShowDemo:false,
      quotationCarId: '',
      carId: '',
      carPhoto: '../../../images/addcar.png',
      licencePlate: '车牌号',
      carTypeName: '车辆类型',
      carBelongName: '车辆所属',
      takeCarAddress:'',
      takeCarArea:'',
      takeCarWay:0,
      carStatus: "车辆灯光",
      carStatusDetail: "正常",
      disposeWay: 0,
      detail: "",
      compulsoryOrderPhoto:'../../../images/jqbd.png',
      buyCompulsoryWay:1,
      contactsName:'',
      contactsPhoneNumber:'',
      validCode:''
    },
    radioList:{
      takeCarWay: [
        { value: 0, text: '专人上门取车', checked: 'true' },
        { value: 1, text: '自行驾车前往' }
      ],
      disposeWay: [
        { value: 0, text: '自行处理', checked: 'true' },
        { value: 1, text: '平台处理' }
      ],
      buyCompulsoryWay: [
        { value: 0, text: '电子保单' },
        { value: 1, text: '纸质保单', checked: 'true' }
      ]
    },
    verCodeText: '获取验证码', //按钮文字
    verCodeSeconds: 61, //倒计时
    verCodeDisabled:false,
    /*地址 */
    region: [],
    /*单选 */
    items: [
      { value: 0, text: '专人上门',checked: 'true' },
      { value: 1, text: '自行驾车'},
    ],

    activeDot: 0,
    activeDotList: util.createDotList(4, 0)
  },

  onLoad: function (e) {
    console.log(e);
    if (e.annualVerificationQuotationId) {
      this.data.annualVerificationQuotationId = e.annualVerificationQuotationId;
      this.getverificationInfo();
    }
  },

  onShow: function () {
    if (this.data.activeDot === 0) {
      if (app.globalData.carInfo) {
        const carInfo = app.globalData.carInfo;
        this.getAvOffer(carInfo.carId, this.data.verificationInfo.takeCarWay)
        this.setData({
          ['verificationInfo.carId']: carInfo.carId,
          ['verificationInfo.carPhoto']: carInfo.carPhoto,
          ['verificationInfo.licencePlate']: carInfo.licencePlate,
          ['verificationInfo.carTypeName']: carInfo.carType,
          ['verificationInfo.carBelongName']: carInfo.carBelong || '个人',

        }, res => {
          app.globalData.carInfo = null;
        })
      }
    }
  },

  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    const targetArea = e.detail.value;
    this.setData({
      region: targetArea,
      ['verificationInfo.takeCarArea']: targetArea.join('')
    })
  },

  onGetCarInfo: function () {
    wx.navigateTo({
      url: '../../vehicleBound/index/index?type=select',
    });
  },

  onInput: function (e) {
    const name = e.currentTarget.dataset.name,
          value = e.detail.value;
    this.data.verificationInfo[name] = value;
  },
  onRadioChange: function (e) {
    const name = e.currentTarget.dataset.name,
          index = e.currentTarget.dataset.index,
          value = e.detail.value;
    if (name === 'carStatusDetail'){
      this.data.annualVerificationQuotationDetail[index].carStatusDetail = value;
    }else{
      this.data.verificationInfo[name] = value;
      const carId = this.data.verificationInfo.quotationCarId || this.data.verificationInfo.carId
      if (name === 'takeCarWay' && carId){
        this.setData({ ['verificationInfo.takeCarWay']: parseInt(value)});
        this.getAvOffer(carId, value)
      }
      if (name === 'buyCompulsoryWay') {
        this.setData({ ['verificationInfo.buyCompulsoryWay']:  parseInt(value) });
      }
    }
  },
  onImageChoose(e) {
    const name = this.data.name;
    this.closePicDemo();
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      success: res => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.info(tempFilePaths);
        this.uploadImage(tempFilePaths[0], name)
          .then(res => {
            this.setData({
              [`verificationInfo.${name}`]: JSON.parse(res.data).data.imgPath
            });
          });
      }
    })
  },

  uploadImage: function (file, name) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '正在上传',
      });
      wx.uploadFile({
        url: 'https://www.shencheyi.com/api/v1/Files/Img',
        filePath: file,
        name: name,
        success: res => {
          wx.hideLoading();
          wx.showToast({
            title: '上传成功',
          });
          resolve(res);
        },

      })
    });

  },

  //发送验证码
  getValidCode: function (e) {
    const phoneNumber = this.data.verificationInfo.contactsPhoneNumber;
    let warn = '';
    if (phoneNumber == '') {
      warn = "号码不能为空";
    } else if (phoneNumber.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phoneNumber)) {
      warn = "手机号格式不正确";
    } else {
      //当手机号正确的时候提示用户短信验证码已经发送
      app.request('/Communication/VerificationCodeForSMS', 'POST',
        { userId: app.globalData.userId, phoneNumber: phoneNumber },
        res => {
          console.log(res);
          this.timer()
          wx.showToast({ title: '已发送', icon: 'success' })
        }, '发送失败');
    };

    //判断 当提示错误信息文字不为空 即手机号输入有问题时提示用户错误信息 并且提示完之后一定要让按钮为可用状态 因为点击按钮时设置了只要点击了按钮就让按钮禁用的情况
    if (warn) {
      wx.showModal({
        title: '提示',
        content: warn
      });
      return;

    };
  },

  timer: function () {
    let verCodeSeconds = this.data.verCodeSeconds;
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          verCodeSeconds --;
          this.setData({
            verCodeText: verCodeSeconds + 's',
            verCodeDisabled:true,
          })
          if (verCodeSeconds <= 0) {
            this.setData({
              verCodeText: '重新发送',
              verCodeSeconds: 61,
              verCodeDisabled: false,
            })
            resolve(setTimer)
          }
        }
        , 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },
  //检查验证码正确性
  checkValidCode:function(){
    return new Promise((resolve,reject) => {
      app.request('/Communication/CheckCode', 'POST',
        { address: this.data.verificationInfo.contactsPhoneNumber, code: this.data.verificationInfo.validCode },
        res => {
          resolve(res);
        },'验证码异常');
    });
  },

  //还未检查参数合法
  submitForm: function () {
    //第一步提交
    (() => {
      // return new Promise((res,rej) => {res()});
      const verificationInfo = this.data.verificationInfo;
      if (this.data.activeDot === 0) {
        let postInfo = {
          userId: app.globalData.userId,
          CarId: verificationInfo.carId || verificationInfo.quotationCarId,
          takeCarWay: verificationInfo.takeCarWay ,
          takeCarAddress: `${verificationInfo.takeCarArea} ${verificationInfo.takeCarAddress}`,
        }
        if (!this.data.agreeCheck) {
          wx.showToast({ title: '请勾选同意《费用协议及风险提示》', icon: 'none', duration: 2000 });
          return;
        }
        //已创建过
        if (this.data.annualVerificationQuotationId) {
          postInfo.annualVerificationId = this.data.annualVerificationQuotationId;
          postInfo.quotationCarId = verificationInfo.quotationCarId || verificationInfo.carId;
          return this.verificationFirst(postInfo);
        } else {
          return this.verificationCreate(postInfo);
        }
      } else if (this.data.activeDot === 1) {
        //第二步
        let postInfo = {
          annualVerificationId: this.data.annualVerificationQuotationId
        };
        postInfo.detailList = this.data.annualVerificationQuotationDetail.map(item => {
          return {
            carStatus: item.annualVerificationQuotationDetail.carStatus,
            carStatusDetail: item.carStatusDetail
          }
        });
        console.log(postInfo)
        return this.verificationSecond(postInfo);
      } else if (this.data.activeDot === 2){
        //第三步
        let postInfo = {
          annualVerificationId: this.data.annualVerificationQuotationId,
          buyCompulsoryWay: verificationInfo.buyCompulsoryWay,
          compulsoryOrderPhoto: verificationInfo.buyCompulsoryWay == 1 ? verificationInfo.compulsoryOrderPhoto : undefined
        };
        if (postInfo.compulsoryOrderPhoto === "../../../images/jqbd.png"){
          wx.showToast({ title: '请上传交强险保单照片', icon: 'none', duration: 2000 });
          return Promise.reject()
        } else {
          console.log(postInfo);
          return this.verificationThirdly(postInfo);
        }
        
      } else {
        //最后一步
        return this.checkValidCode()
          .then(() => {
            let postInfo = {
              annualVerificationId: this.data.annualVerificationQuotationId,
              contactsName:verificationInfo.contactsName,
              contactsPhoneNumber: verificationInfo.contactsPhoneNumber
            };
            console.log(postInfo);
            return this.verificationFourthly(postInfo);
          });
      }
    })()
      .then(res => {
        if (this.data.activeDot !== 3) {
          this.nextStep();
        } else {
          console.log('年审付款', res);
          this.payFn(res)
        }
      });
  },
  // 付款
  payFn(e) {
    app.request('/WeChat/Unifiedorder', 'POST', {
      userId: e.userId,
      orderId: e.orderId
    }, res => {
      wx.requestPayment({
        ...res,
        success: res => {
          wx.showModal({
            title: '提示',
            content: '年审订单已经提交成功，客服会尽快与您取得联系，商讨业务细节',
            showCancel: false,
            success: () => {
              wx.navigateBack();
            }
          });
        },
        fail: res => {
          wx.showToast({ title: '支付失败', icon: 'none', duration: 2000 });
          wx.navigateBack();
        }
      })
    });
  },
  verificationFirst: function (postInfo) {
    return new Promise((resolve, reject) => {
      app.request('/AnnualVerification/AnnualVerificationFirst', 'PUT', postInfo,
        res => {
          resolve(res);
        }, '信息保存失败');
    });
  },
  verificationSecond: function (postInfo) {
    return new Promise((resolve, reject) => {
      app.request('/AnnualVerification/AnnualVerificationSecond', 'PUT', postInfo,
        res => {
          resolve(res);
        }, '信息保存失败');
    });
  },
  verificationThirdly: function (postInfo) {
    const verificationInfo = this.data.verificationInfo;
    return new Promise((resolve, reject) => {
      //参数检查
      if (verificationInfo.buyCompulsoryWay == 1) {
        if (verificationInfo.compulsoryOrderPhoto.indexOf('https://www.') === -1) {
          wx.showToast({
            title: '需上传交强保单照片',
            icon: 'none'
          });
          reject();
        }
      }

      app.request('/AnnualVerification/AnnualVerificationThirdly', 'PUT', postInfo,
        res => {
          resolve(res);
        }, '信息保存失败');
    });
  },
  verificationFourthly: function (postInfo){
    return new Promise((resolve, reject) => {
      app.request('/AnnualVerification/AnnualVerificationFourthly', 'PUT', postInfo,
        res => {
          wx.showToast({
            title: '新建年审成功',
          });
          resolve(res);
        }, '信息保存失败');
    });
  },
  verificationCreate: function (postInfo) {
    return new Promise((resolve, reject) => {
      app.request('/AnnualVerification/Create', 'POST', postInfo,
        res => {
          this.data.annualVerificationQuotationId = res.annualVerificationQuotationId;
          resolve(res);
        }, '保险单创建失败');
    });
  },
  //加载年审具体信息
  getverificationInfo: function () {
    app.request('/AnnualVerification/AnnualVerification', 'GET', { annualVerificationId: this.data.annualVerificationQuotationId },
      res => {
        console.log('加载年审具体信息', res);
        res.annualVerificationQuotation.carPhoto = res.annualVerificationQuotation.carPhoto || '../../../images/upload.png';
        res.annualVerificationQuotation.carPhoto = res.SCY_QuotationCarModel.carPhoto;
        res.annualVerificationQuotation.licencePlate = res.SCY_QuotationCarModel.licencePlate;
        res.annualVerificationQuotation.carTypeName = res.SCY_QuotationCarModel.carTypeName;
        res.annualVerificationQuotation.carStatus = res.annualVerificationQuotationDetail[0].carStatus;
        res.annualVerificationQuotation.carStatusDetail = res.annualVerificationQuotationDetail[0].carStatusDetail;
        res.annualVerificationQuotation.disposeWay = res.annualVerificationQuotationDetail[0].disposeWay;
        res.annualVerificationQuotation.detail = res.annualVerificationQuotationDetail[0].detail;
        res.annualVerificationQuotation.takeCarArea = res.annualVerificationQuotation.takeCarAddress.split(' ')[0];
        res.annualVerificationQuotation.takeCarAddress = res.annualVerificationQuotation.takeCarAddress.split(' ')[1];
        res.annualVerificationQuotation.compulsoryOrderPhoto = res.annualVerificationQuotation.compulsoryOrderPhoto ? res.annualVerificationQuotation.compulsoryOrderPhoto : '../../../images/jqbd.png';
        for (let key in this.data.radioList){
            this.data.radioList[key].forEach(item => {
              if (item.value == res.annualVerificationQuotation[key]) {
            item.checked = true;
          } else {
            item.checked = false;
          }
            });
        }
        this.getAvOffer(res.annualVerificationQuotation.quotationCarId, res.annualVerificationQuotation.takeCarWay)
        this.setData({
          verificationInfo: res.annualVerificationQuotation
,
          radioList: this.data.radioList,
          agreeCheck: true
        });
      }, '获取失败');
  },
  //获取车辆情况选项
  getverificationDetail: function () {
    
    app.request('/AnnualVerification/AnnualVerificationDedail', 'GET', { annualVerificationId: this.data.annualVerificationQuotationId },
      res => {
        console.log('加载年审车辆情况选项', res);
        res.annualVerificationQuotationDetailList.forEach(item => {
          //item.carStatusDetailList = JSON.parse(JSON.stringify(carStatusDetailList)) ;

          item.carStatusDetailList[0].checked = true;
          if (!!item.annualVerificationQuotationDetail.carStatusDetail){
            item.carStatusDetailList.forEach(csd => {
              if (csd.name === item.annualVerificationQuotationDetail.carStatusDetail){
                csd.checked = true;
                item.carStatusDetail = csd.name;
              }else{
                csd.checked = false;
              }
            });
          }else{
            //默认正常
            item.carStatusDetail = item.carStatusDetailList[0].name;
          }
        });
        this.setData({
          annualVerificationQuotationDetail: res.annualVerificationQuotationDetailList
        });
      }, '获取失败');
  },


  nextStep: function () {
    let activeDot = this.data.activeDot;
    // 提交表单之后
    if (activeDot < 4) {
      this.setData({
        activeDot: activeDot + 1,
        activeDotList: util.createDotList(4, activeDot + 1)
      },()=>{
        //监控到达第二步时加载车辆信息选项信息
        if (this.data.activeDot === 1){
          this.getverificationDetail();
        }
      });
    }
    


    wx.setNavigationBarTitle({
      title: `新建年审-${barTitleText[this.data.activeDot]}`
    })
  },
  //上一步
  prevStep: function () {
    let activeDot = this.data.activeDot,
      prevDot = activeDot - 1; 
    let way = this.data.verificationInfo.compulsoryOrderPhoto === '../../../images/jqbd.png' ? 1 : 0;
    // 提交表单之后
    if (activeDot < 4) {
      this.setData({
        ['verificationInfo.buyCompulsoryWay']: way,
        activeDot: prevDot,
        activeDotList: util.createDotList(4, prevDot)
      }, () => {
        wx.setNavigationBarTitle({
          title: `添加车辆-${barTitleText[prevDot]}`
        })
      });
    }
  },

  openPicDemo: function (e) {
    this.setData({
      currentTapPic: e.target.id,
      isShowDemo: true,
      demoSrc: 'https://www.shencheyi.com/Files/TempletPhoto/SALI.jpg'
    })
  },

  closePicDemo: function () {
    this.setData({
      isShowDemo: false,
      currentTapPic: ''
    })
  },
  //获取年审服务费
  getAvOffer: function (quotationCarId, takeCarWay) {
    app.request('/CarType/AVOffer', 'GET', {quotationCarId, takeCarWay},
      res => {
        this.setData({price:res})
      });
  },

  handleAgreeCheck: function () {
    this.data.agreeCheck = !this.data.agreeCheck
  }

})